<!---
  * 统一下拉选择框
  *
-->
<template>
  <div>
    <a-select
      v-model:value="selectValue"
      :style="`width: ${width}`"
      :placeholder="props.placeholder"
      :allowClear="true"
      :size="size"
      :mode="mode"
      @change="onChange"
      :disabled="disabled"
    >
      <a-select-option v-for="item in keyValList" :key="item.key" :value="item.key">
        {{ item.value }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue';
  import { reportApi } from '/@/api/task/report-api';
  import { SELECT_TYPE_ENUM } from '/@/constants/system/common-select-const';

  const props = defineProps({
    selectType: String,
    value: String,
    mode: {
      type: String,
      default: 'combobox',
    },
    width: {
      type: String,
      default: '100%',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    size: {
      type: String,
      default: 'default',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  });

  // -------------------------- 查询 字典数据 --------------------------

  const keyValList = ref([]);
  async function querySelect() {
    let res = {success:false,data:[]};
    if(props.selectType===SELECT_TYPE_ENUM.TM_HAS_ROOT_PROJECT.value)
      res=await reportApi.getHasRootProject();
    if(props.selectType===SELECT_TYPE_ENUM.COMMON_HAS_DEPT.value)
      res=await reportApi.getHasDept();

    if(res.success){
      keyValList.value = res.data;
    }
  }

  const values = computed(() => {
    if (!props.value) {
      return [];
    }
    if (!Array.isArray(props.value)) {
      console.error('valueList is not array!!!');
      return [];
    }
    let res = [];
    if (props.value && props.value.length > 0) {
      props.value.forEach((element) => {
        res.push(element.key);
      });
      return res;
    }
    return res;
  });

  onMounted(querySelect);

  // -------------------------- 选中 相关、事件 --------------------------

  const selectValue = ref(props.value);
  watch(
    () => props.value,
    (value) => {
      selectValue.value = value;
    }
  );

  const emit = defineEmits(['update:value', 'change']);
  function onChange(value) {
    let selected = '';
    if (!value) {
      emit('update:value', selected);
      emit('change', selected);
      return selected;
    }
    if (Array.isArray(props.value)) {
      let valueList = keyValList.value.filter((e) => value.includes(e.key));
      valueList = valueList.map((e) => e.key);
      emit('update:value', valueList);
      emit('change', valueList);
    } else {
      let findValue = keyValList.value.find((e) => e.key == value);
      emit('update:value', findValue.key);
      emit('change', findValue.key);
    }
  }
</script>
